package sf.querydsl;

import sf.core.DBObject;
import sf.database.dao.DBContext;
import sf.database.meta.MetaHolder;
import sf.database.meta.TableMapping;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class QueryDSLTables {
    private static Map<Class, SQLRelationalPath> sqlRelationalPathBaseMap = new ConcurrentHashMap<>();

    /**
     * @param clz
     * @return
     */
    public static JPAEntityPath entityPathBase(DBContext context, Class<? extends DBObject> clz) {
        JPAEntityPath pb = new JPAEntityPath(context, clz);
        return pb;
    }

    /**
     * @param classMap
     */
    public static void initRelationalPathBase(Map<Class<?>, TableMapping> classMap) {
        for (Map.Entry<Class<?>, TableMapping> entry : classMap.entrySet()) {
            SQLRelationalPath pb = new SQLRelationalPath(entry.getKey());
            sqlRelationalPathBaseMap.put(entry.getKey(), pb);
        }
    }

    /**
     * @param clz
     * @param <T>
     * @return
     */
    public static <T extends DBObject> SQLRelationalPath<T> relationalPathBase(Class<T> clz) {
        return relationalPathBase(null, clz);
    }

    /**
     * @param clz
     * @param <T>
     * @return
     */
    public static <T extends DBObject> SQLRelationalPath<T> relationalPathBase(DBContext context, Class<T> clz) {
        TableMapping tm = MetaHolder.getMeta(clz);
        SQLRelationalPath pb = relationalPathBase(context, tm);
        return pb;
    }

    /**
     * @param tm
     * @param <T>
     * @return
     */
    public static <T extends DBObject> SQLRelationalPath<T> relationalPathBase(TableMapping tm) {
        return relationalPathBase(null, tm);
    }

    /**
     * @param tm
     * @param <T>
     * @return
     */
    public static <T extends DBObject> SQLRelationalPath<T> relationalPathBase(DBContext context, TableMapping tm) {
        SQLRelationalPath pb = sqlRelationalPathBaseMap.get(tm.getThisType());
        if (pb == null) {
            pb = new SQLRelationalPath(context, tm);
            sqlRelationalPathBaseMap.put(tm.getThisType(), pb);
        }
        return pb;
    }
}
